package com.cwz.core.feign;

import com.cwz.core.constant.SecurityConstants;
import com.cwz.core.constant.TokenConstants;
import com.cwz.core.utils.ip.IpUtils;
import com.cwz.core.utils.servle.ServletUtils;
import com.cwz.core.utils.string.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @program: w-demo
 * @description: feign 请求拦截器
 * @author: Wen
 **/
public class FeignRequestInterceptor implements RequestInterceptor {

	@Override
	public void apply(RequestTemplate requestTemplate) {
		HttpServletRequest request = ServletUtils.getRequest();
		if (StringUtils.isNotNull(request)) {
			Map<String, String> headers = ServletUtils.getHeaders(request);

			// 传递用户信息请求头，防止丢失
			String userId = headers.get(SecurityConstants.DETAILS_USER_ID);
			if (StringUtils.isNotEmpty(userId)) {
				requestTemplate.header(SecurityConstants.DETAILS_USER_ID, userId);
			}
			String userName = headers.get(SecurityConstants.DETAILS_USERNAME);
			if (StringUtils.isNotEmpty(userName)) {
				requestTemplate.header(SecurityConstants.DETAILS_USERNAME, userName);
			}
			String userKey = headers.get(SecurityConstants.USER_KEY);
			if (StringUtils.isNotEmpty(userKey)) {
				requestTemplate.header(SecurityConstants.USER_KEY, userKey);
			}
			String company = headers.get(SecurityConstants.DETAILS_COMPANY);
			if (StringUtils.isNotEmpty(company)) {
				requestTemplate.header(SecurityConstants.DETAILS_COMPANY, company);
			}
			String authentication = headers.get(TokenConstants.AUTHENTICATION);
			if (StringUtils.isNotEmpty(authentication)) {
				requestTemplate.header(TokenConstants.AUTHENTICATION, authentication);
			}

			// 配置客户端IP
			requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));
		}
	}
}
